##############################################################################
## plot.cna
##
## Description:
##   'plot.cna' plots copy number data.
## 
## Usage:
##   plot.cna(copyNumber, chrID, segMean)
##
## Arguments:
##   copyNumber: a vector of copy number profile.
##   chrID: a character vector of chromosome ID.
##   segMean: segmental means.
##
## Example:
##   plot.cna(copyNumber, chrID, segMean)
##
## Author:
##   Bai Zhang    baizhang@vt.edu
##
##############################################################################


plot.cna <- function(copyNumber, chrID, segMean, ylim = c(-1, 6)) {

  for (chr in unique(chrID)) {

    cn <- copyNumber[chrID == chr]
    mean <- segMean[chrID == chr]

    X11(width = 12, height = 6)
    plot(cn, pch = ".", col = "#888888", ylim = ylim, xlab = paste("Chr ", chr), ylab = "Copy number", cex.lab=1.5)

    grid()
    
    segment <- profile2segment(segMean)

    
    
    ## require(graphics)
    ## blue2white2red <- c("#0000FF", "#AAAAAA", "#FF0000")
    ## color.palette <- colorRampPalette(blue2white2red, space = "rgb")
    ## colorKey <- color.palette(100)

    for (i in 1:length(segment$seg.mean)) {
      if (segment$seg.mean[i] < 1.9) {
        seg.color <- "#0000FF"
      } else if (segment$seg.mean[i] > 2.1) {
        seg.color <- "#FF0000"
      } else {
        seg.color <- "#00FF00"
      }
      
      lines(x=c(segment$seg.start[i], segment$seg.end[i]), y=c(segment$seg.mean[i], segment$seg.mean[i]), col=seg.color, lwd=3)

    }


    ## cn.color <- numeric(length(cn))
    ## cn.color[which(cn <= 2)] <- round(cn[cn <= 2] * 25)
    ## cn.color[which(cn > 2)] <- round((cn[cn > 2] - 2) / (max(cn)-2) * 50) + 50
    ## cn.color <- colorKey[cn.color]

    
    ## X11(width = 12, height = 6)
    ## plot(cn, pch = ".", col = cn.color, ylim = ylim, xlab = paste("Chr ", chr), ylab = "copy number")
    
    
  }
  
  
}


profile2segment <- function(segMean) {

  x <- segMean
  x.shifted <- c(x[-1], x[length(x)])
  x <- x - x.shifted
  seg.start <- c(1, which(x != 0)+1)
  seg.end <- c(which(x != 0), length(x))
  seg.mean <- c(segMean[seg.start])

  segment <- list(seg.start=seg.start, seg.end=seg.end, seg.mean=seg.mean)

  segment
  
}

